package com.ceo.common.threadlocal;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author uto_dev_008
 * @desc
 * @since 2021/11/24 10:32
 * Copyright (c)  All rights reserved
 */
public class GlobalMemcache {
    private static Map<String, InheritableThreadLocal<Object>> threadLocalMap = new ConcurrentHashMap<String, InheritableThreadLocal<Object>>();

    private static byte[] lock = new byte[0];

    public static void setL(String key, Object obj) {
        InheritableThreadLocal<Object> tl = threadLocalMap.get(key);
        if (obj == null) {
            if (tl != null) {
                tl.set(null);
            }
            return;
        }
        if (tl == null) {
            synchronized (lock) {
                if (tl == null) {
                    tl = new InheritableThreadLocal<Object>();
                }
            }
        }
        tl.set(obj);
        threadLocalMap.put(key, tl);
    }

    public static Object getL(String key) {
        InheritableThreadLocal<Object> tl = threadLocalMap.get(key);
        if (tl == null) {
            return null;
        }
        return tl.get();
    }
}
